﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace Fis
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }

        bool isLock = false;
        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (isLock)
                return;

            isLock = true;
            if (HasUpdatePackage())
            {
                DoUpdate();
            }

            RunApplication();
            this.Invoke(new Action(Close) as Delegate);

            timer.Stop();
            isLock = false;
        }

        string update = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "update", "update.xap");
        System.Timers.Timer timer = new System.Timers.Timer(2000);

        private void Form1_Load(object sender, EventArgs e)
        {


        }

        bool HasUpdatePackage()
        {
            return File.Exists(update);
        }

        void DoUpdate()
        {
            var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(update)))
            {
                for (var entry = s.GetNextEntry(); entry != null; entry = s.GetNextEntry())
                {
                    var entryPath = Path.Combine(baseDirectory, entry.Name);

                    if (entry.IsDirectory)
                    {
                        if (!Directory.Exists(entryPath))
                            Directory.CreateDirectory(entryPath);
                    }
                    else if (entry.IsFile)
                    {
                        using (var write = new System.IO.FileStream(entryPath, FileMode.Create, FileAccess.Write))
                        {
                            s.CopyTo(write);
                        }
                    }
                }
            }
            File.Delete(update);
        }

        void RunApplication()
        {
            if (File.Exists("Fis.Win.exe"))
                System.Diagnostics.Process.Start("Fis.Win.exe");
        }
    }
}
